package cn.murky.tenant.system.biz.service.impl;

import cn.murky.core.exception.ServiceException;
import cn.murky.core.record.PasswordRecord;
import cn.murky.core.utils.EncryptionUtil;
import cn.murky.tenant.system.biz.domian.dto.ResetPasswordDTO;
import cn.murky.tenant.system.biz.domian.entity.TenantUser;
import cn.murky.tenant.system.biz.mapper.TenantUserMapper;
import cn.murky.tenant.system.biz.service.ITenantUserService;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import org.noear.solon.annotation.Component;

import java.util.Optional;

import static cn.murky.tenant.system.api.constant.ErrorConstant.CONFIRM_PASSWORD_ERROR;
import static cn.murky.tenant.system.api.constant.ErrorConstant.USER_NOT_EXIST;

@Component
public class ITenantUserServiceImpl extends ServiceImpl<TenantUserMapper, TenantUser> implements ITenantUserService {
    @Override
    public TenantUser getByAccount(String account) {
        return mapper.selectByAccount(account);
    }

    @Override
    public boolean resetPassword(ResetPasswordDTO resetPasswordDto) {
        if (!resetPasswordDto.getPassword().equals(resetPasswordDto.getConfirmPassword())) {
            throw new ServiceException(CONFIRM_PASSWORD_ERROR);
        }
        Long userId = resetPasswordDto.getId();
        TenantUser tenantUser = mapper.selectOneById(userId);
        // 校验账号是否正确
        Optional.ofNullable(tenantUser).orElseThrow(() -> new ServiceException(USER_NOT_EXIST));
        // 加密获取新的密码和盐值
        PasswordRecord passwordRecord = EncryptionUtil.userEncryption(resetPasswordDto.getPassword());
        int count = mapper.resetPassword(userId, passwordRecord.password(),passwordRecord.salt());
        return count > 0;
    }
}
